package com.imut.lagain.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.imut.lagain.entity.AnxietySession;
import com.imut.lagain.entity.ThoughtAnalysis;
import com.imut.lagain.entity.BreathingExercise;
import com.imut.lagain.entity.SensoryExercise;
import com.imut.lagain.service.IAnxietyReliefService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 焦虑安抚空间控制器
 */
@RestController
@RequestMapping("/api/anxiety-relief")
@CrossOrigin(origins = "*")
public class AnxietyReliefController {
    private static final Logger log = LoggerFactory.getLogger(AnxietyReliefController.class);

    @Autowired
    private IAnxietyReliefService anxietyReliefService;

    /**
     * 开始焦虑安抚会话
     */
    @PostMapping("/session/start")
    public ResponseEntity<Map<String, Object>> startSession(@RequestBody SessionStartRequest request) {
        try {
            AnxietySession session = anxietyReliefService.startAnxietySession(
                request.getUserId(), 
                request.getInitialAnxietyLevel(), 
                java.util.Arrays.asList(request.getTrigger())
            );
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("sessionId", session.getId());
            result.put("status", "started");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 完成焦虑安抚会话
     */
    @PostMapping("/session/{sessionId}/complete")
    public ResponseEntity<Map<String, Object>> completeSession(
            @PathVariable Long sessionId,
            @RequestBody SessionCompleteRequest request) {
        try {
            Map<String, Object> result = anxietyReliefService.completeAnxietySession(
                sessionId,
                request.getFinalAnxietyLevel(),
                request.getFeedback()
            );
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 开始呼吸练习
     */
    @PostMapping("/breathing/start")
    public ResponseEntity<Map<String, Object>> startBreathingExercise(@RequestBody BreathingStartRequest request) {
        try {
            BreathingExercise exercise = anxietyReliefService.startBreathingExercise(
                request.getUserId(),
                request.getSessionId(),
                request.getExerciseType(),
                request.getDuration(),
                request.getAnxietyLevel()
            );
            Map<String, Object> result = new HashMap<>();
            result.put("exerciseId", exercise.getId());
            // 修复：使用服务实现类中的方法获取真实的指导说明
            result.put("instructions", getBreathingInstructions(request.getExerciseType()));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 更新呼吸练习进度
     */
    @PostMapping("/breathing/{exerciseId}/progress")
    public ResponseEntity<Map<String, Object>> updateBreathingProgress(
            @PathVariable Long exerciseId,
            @RequestBody BreathingProgressRequest request) {
        try {
            Boolean success = anxietyReliefService.updateBreathingProgress(
                exerciseId,
                request.getCyclesCompleted(),
                request.getCurrentAnxietyLevel()
            );
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 完成呼吸练习
     */
    @PostMapping("/breathing/{exerciseId}/complete")
    public ResponseEntity<Map<String, Object>> completeBreathingExercise(@PathVariable Long exerciseId) {
        try {
            Map<String, Object> result = anxietyReliefService.completeBreathingExercise(exerciseId);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 开始感官安抚练习
     */
    @PostMapping("/sensory/start")
    public ResponseEntity<Map<String, Object>> startSensoryExercise(@RequestBody SensoryStartRequest request) {
        try {
            SensoryExercise exercise = anxietyReliefService.getSensoryExercise(
                request.getUserId(),
                "all", // 默认使用所有感官
                "indoor" // 默认室内环境
            );
            Map<String, Object> result = new HashMap<>();
            result.put("exerciseId", exercise.getId());
            // 修复：使用服务实现类中的方法获取真实的指导说明
            result.put("instructions", getSensoryInstructions("all", "indoor"));
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 提交感官练习结果
     */
    @PostMapping("/sensory/{exerciseId}/result")
    public ResponseEntity<Map<String, Object>> submitSensoryResult(
            @PathVariable Long exerciseId,
            @RequestBody SensoryResultRequest request) {
        try {
            Boolean success = anxietyReliefService.recordSensoryResult(
                exerciseId, // 使用exerciseId而不是session
                "all", // 感官类型
                java.util.Arrays.asList(
                    request.getSeeItems(),
                    request.getTouchItems(),
                    request.getHearItems(),
                    request.getSmellItems(),
                    request.getTasteItems()
                ),
                5 // 默认效果评分
            );
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 开始思维拆解分析
     */
    @PostMapping("/thought-analysis/start")
    public ResponseEntity<Map<String, Object>> startThoughtAnalysis(@RequestBody ThoughtAnalysisRequest request) {
        try {
            ThoughtAnalysis analysis = anxietyReliefService.startThoughtAnalysis(
                request.getSessionId(),
                request.getAnxiousThought()
            );
            Map<String, Object> result = new HashMap<>();
            result.put("analysisId", analysis.getId());
            result.put("guidingQuestions", analysis.getSuggestions() != null ? analysis.getSuggestions() : "请思考这个问题...");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 提交认知重构结果
     */
    @PostMapping("/thought-analysis/{analysisId}/restructure")
    public ResponseEntity<Map<String, Object>> submitCognitiveRestructuring(
            @PathVariable Long analysisId,
            @RequestBody CognitiveRestructuringRequest request) {
        try {
            Map<String, String> answers = new HashMap<>();
            answers.put("evidenceFor", request.getEvidenceFor());
            answers.put("evidenceAgainst", request.getEvidenceAgainst());
            answers.put("cognitiveDistortions", request.getCognitiveDistortions());
            
            Map<String, Object> result = anxietyReliefService.performCognitiveRestructuring(
                analysisId,
                answers
            );
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 生成替代思维
     */
    @PostMapping("/thought-analysis/{analysisId}/alternatives")
    public ResponseEntity<Map<String, Object>> generateAlternativeThoughts(
            @PathVariable Long analysisId,
            @RequestBody AlternativeThoughtsRequest request) {
        try {
            List<String> alternatives = anxietyReliefService.generateAlternativeThoughts(
                analysisId,
                request.getOriginalThought()
            );
            Map<String, Object> result = new HashMap<>();
            result.put("alternatives", alternatives);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取安抚历史记录
     */
    @GetMapping("/history/{userId}")
    public ResponseEntity<Map<String, Object>> getComfortHistory(
            @PathVariable Long userId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            List<AnxietySession> history = anxietyReliefService.getComfortHistory(userId, startDate, endDate);
            Map<String, Object> result = new HashMap<>();
            result.put("history", history);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 分析焦虑模式
     */
    @GetMapping("/analysis/patterns/{userId}")
    public ResponseEntity<Map<String, Object>> analyzeAnxietyPatterns(@PathVariable Long userId) {
        try {
            Map<String, Object> patterns = anxietyReliefService.analyzeAnxietyPatterns(userId);
            return ResponseEntity.ok(patterns);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取进步报告
     */
    @GetMapping("/progress/{userId}")
    public ResponseEntity<Map<String, Object>> getProgressReport(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "month") String period) {
        try {
            Map<String, Object> progress = anxietyReliefService.getProgressReport(userId, period);
            return ResponseEntity.ok(progress);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 设置安抚提醒
     */
    @PostMapping("/reminders")
    public ResponseEntity<Map<String, Object>> setComfortReminder(@RequestBody ReminderRequest request) {
        try {
            Map<String, Object> settings = new HashMap<>();
            settings.put("frequency", request.getFrequency());
            settings.put("timeOfDay", request.getTimeOfDay());
            settings.put("message", request.getMessage());
            
            Boolean success = anxietyReliefService.setReliefReminder(
                request.getUserId(),
                request.getReminderType(),
                settings
            );
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    /**
     * 获取紧急安抚方案
     */
    @GetMapping("/emergency/{userId}")
    public ResponseEntity<Map<String, Object>> getEmergencyComfort(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "moderate") String severity) {
        try {
            Map<String, Object> result = anxietyReliefService.getEmergencyReliefPlan(userId, severity);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    // DTO类定义
    public static class SessionStartRequest {
        private Long userId;
        private Integer initialAnxietyLevel;
        private String trigger;
        
        // getters and setters
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Integer getInitialAnxietyLevel() { return initialAnxietyLevel; }
        public void setInitialAnxietyLevel(Integer initialAnxietyLevel) { this.initialAnxietyLevel = initialAnxietyLevel; }
        public String getTrigger() { return trigger; }
        public void setTrigger(String trigger) { this.trigger = trigger; }
    }

    public static class SessionCompleteRequest {
        private Integer finalAnxietyLevel;
        private String feedback;
        
        public Integer getFinalAnxietyLevel() { return finalAnxietyLevel; }
        public void setFinalAnxietyLevel(Integer finalAnxietyLevel) { this.finalAnxietyLevel = finalAnxietyLevel; }
        public String getFeedback() { return feedback; }
        public void setFeedback(String feedback) { this.feedback = feedback; }
    }

    public static class BreathingStartRequest {
        private Long userId;
        private Long sessionId;
        private String exerciseType;
        private Integer duration;
        private Integer anxietyLevel;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Long getSessionId() { return sessionId; }
        public void setSessionId(Long sessionId) { this.sessionId = sessionId; }
        public String getExerciseType() { return exerciseType; }
        public void setExerciseType(String exerciseType) { this.exerciseType = exerciseType; }
        public Integer getDuration() { return duration; }
        public void setDuration(Integer duration) { this.duration = duration; }
        public Integer getAnxietyLevel() { return anxietyLevel; }
        public void setAnxietyLevel(Integer anxietyLevel) { this.anxietyLevel = anxietyLevel; }
    }

    public static class BreathingProgressRequest {
        private Integer cyclesCompleted;
        private Integer currentAnxietyLevel;
        
        public Integer getCyclesCompleted() { return cyclesCompleted; }
        public void setCyclesCompleted(Integer cyclesCompleted) { this.cyclesCompleted = cyclesCompleted; }
        public Integer getCurrentAnxietyLevel() { return currentAnxietyLevel; }
        public void setCurrentAnxietyLevel(Integer currentAnxietyLevel) { this.currentAnxietyLevel = currentAnxietyLevel; }
    }

    public static class SensoryStartRequest {
        private Long userId;
        private Long sessionId;
        private Integer anxietyLevel;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Long getSessionId() { return sessionId; }
        public void setSessionId(Long sessionId) { this.sessionId = sessionId; }
        public Integer getAnxietyLevel() { return anxietyLevel; }
        public void setAnxietyLevel(Integer anxietyLevel) { this.anxietyLevel = anxietyLevel; }
    }

    public static class SensoryResultRequest {
        private String seeItems;
        private String touchItems;
        private String hearItems;
        private String smellItems;
        private String tasteItems;
        private Integer anxietyAfter;
        
        public String getSeeItems() { return seeItems; }
        public void setSeeItems(String seeItems) { this.seeItems = seeItems; }
        public String getTouchItems() { return touchItems; }
        public void setTouchItems(String touchItems) { this.touchItems = touchItems; }
        public String getHearItems() { return hearItems; }
        public void setHearItems(String hearItems) { this.hearItems = hearItems; }
        public String getSmellItems() { return smellItems; }
        public void setSmellItems(String smellItems) { this.smellItems = smellItems; }
        public String getTasteItems() { return tasteItems; }
        public void setTasteItems(String tasteItems) { this.tasteItems = tasteItems; }
        public Integer getAnxietyAfter() { return anxietyAfter; }
        public void setAnxietyAfter(Integer anxietyAfter) { this.anxietyAfter = anxietyAfter; }
    }

    public static class ThoughtAnalysisRequest {
        private Long userId;
        private Long sessionId;
        private String anxiousThought;
        private Integer anxietyLevel;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public Long getSessionId() { return sessionId; }
        public void setSessionId(Long sessionId) { this.sessionId = sessionId; }
        public String getAnxiousThought() { return anxiousThought; }
        public void setAnxiousThought(String anxiousThought) { this.anxiousThought = anxiousThought; }
        public Integer getAnxietyLevel() { return anxietyLevel; }
        public void setAnxietyLevel(Integer anxietyLevel) { this.anxietyLevel = anxietyLevel; }
    }

    public static class CognitiveRestructuringRequest {
        private String evidenceFor;
        private String evidenceAgainst;
        private String cognitiveDistortions;
        
        public String getEvidenceFor() { return evidenceFor; }
        public void setEvidenceFor(String evidenceFor) { this.evidenceFor = evidenceFor; }
        public String getEvidenceAgainst() { return evidenceAgainst; }
        public void setEvidenceAgainst(String evidenceAgainst) { this.evidenceAgainst = evidenceAgainst; }
        public String getCognitiveDistortions() { return cognitiveDistortions; }
        public void setCognitiveDistortions(String cognitiveDistortions) { this.cognitiveDistortions = cognitiveDistortions; }
    }

    public static class AlternativeThoughtsRequest {
        private String originalThought;
        private String thoughtCategory;
        
        public String getOriginalThought() { return originalThought; }
        public void setOriginalThought(String originalThought) { this.originalThought = originalThought; }
        public String getThoughtCategory() { return thoughtCategory; }
        public void setThoughtCategory(String thoughtCategory) { this.thoughtCategory = thoughtCategory; }
    }

    public static class ReminderRequest {
        private Long userId;
        private String reminderType;
        private String frequency;
        private String timeOfDay;
        private String message;
        
        public Long getUserId() { return userId; }
        public void setUserId(Long userId) { this.userId = userId; }
        public String getReminderType() { return reminderType; }
        public void setReminderType(String reminderType) { this.reminderType = reminderType; }
        public String getFrequency() { return frequency; }
        public void setFrequency(String frequency) { this.frequency = frequency; }
        public String getTimeOfDay() { return timeOfDay; }
        public void setTimeOfDay(String timeOfDay) { this.timeOfDay = timeOfDay; }
        public String getMessage() { return message; }
        public void setMessage(String message) { this.message = message; }
    }

    // 添加获取呼吸练习指导说明的辅助方法
    private String getBreathingInstructions(String exerciseType) {
        switch (exerciseType) {
            case "4-7-8":
                return "吸气4秒，屏住呼吸7秒，呼气8秒。这种方法有助于激活副交感神经系统，快速缓解焦虑。";
            case "box_breathing":
                return "吸气4秒，屏住4秒，呼气4秒，暂停4秒。想象画一个正方形，每条边对应一个步骤。";
            case "deep_breathing":
                return "深深吸气6秒，短暂屏住2秒，缓慢呼气8秒。专注于腹部的起伏，让呼吸变得深长。";
            default:
                return "跟随引导进行呼吸练习，专注于呼吸的节奏。";
        }
    }

    // 添加获取感官练习指导说明的辅助方法
    private String getSensoryInstructions(String senseType, String environment) {
        return "专注于你的" + senseType + "感官，在" + environment + "环境中寻找相应的感官体验。";
    }
}